package com.fr71.project.dm.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * RSA加密解密
 *
 * @author ruoyi
 **/
public class RsaUtils {
//    // Rsa 私钥
//    public static String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANUWcg3cinRjPs2IQUs1b5tuKV1g+GjFcXON995zQjSkPYNqt3JCkD1R3iWd8AirjlIkHCPrn5g5PZOfoxfBxkoA1lKbkMoseq6BjvgA5JJuqWWv2WMHklKnxA6l8TMo6z6KZ0e8bO3ZDg8VA34nOfHFteYSMan3GJBWIpREUjtjAgMBAAECgYAWKjSI7pTUUHJ67J5mFVPbphTVar3MICWR8IWE9RZA5Yikf9g/IV9hkX97CDesnzO5pZnrvpmmOuYF0ggj83sNjNUlX6vabX4IrbwSqZeskbHSHClJDm20UBgyKuE9ij9kIzuyxC30Hnw0kOE3hAJR5L+K3LRzoQrFNMqRzkxtMQJBAPy4hopiMz7AaKi5LglvjQsjgay7yqdZx+k7f96BHLiAA4XXKH4FVYo5ETL+Lle5WFAC+jLB+QVskUUPocGf47sCQQDX2kTOtFANhJC8mr2MkXFXHaaAML057PUG/fBqGlaGKiyJUdJDrDGCJ66RQIStTC3K0Mpw8WzEN69R+W0gaUh5AkB9PIBHwYQ9m6IBwsrCmEof8/eF/wXdSsublAW44Oi3sZCNWeNSGBicx8zzJS0YAdx2whL05lUeT//pZma1iiOTAkAGAD11ebHYDl1vwOWQKOL7xwk/+xrnp1zQivLKIF1TcYy3bJzp4Lmnoq7Jvv9xSfLj9pYKOcwKUHoBT2vnQMYRAkEAtwGb0vvQ54eMz9nWds4mExy355KLiDD1OPeD1IE/5d0YahKcSm/h39uRO0n2K5+roE7p+ZWE9hjcxZr3emTkSw==";
//
//    public static String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDVFnIN3Ip0Yz7NiEFLNW+bbildYPhoxXFzjffec0I0pD2DardyQpA9Ud4lnfAIq45SJBwj65+YOT2Tn6MXwcZKANZSm5DKLHqugY74AOSSbqllr9ljB5JSp8QOpfEzKOs+imdHvGzt2Q4PFQN+JznxxbXmEjGp9xiQViKURFI7YwIDAQAB";

//    /**
//     * 私钥解密
//     *
//     * @param text 待解密的文本
//     * @return 解密后的文本
//     */
//    public static String decryptByPrivateKey(String text) throws Exception {
//        return decryptByPrivateKey(privateKey, text);
//    }

//    /**
//     * 公钥解密
//     *
//     * @param text 待解密的信息
//     * @return 解密后的文本
//     */
//    public static String decryptByPublicKey(String text) throws Exception {
//        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
//        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
//        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
//        Cipher cipher = Cipher.getInstance("RSA");
//        cipher.init(Cipher.DECRYPT_MODE, publicKey);
//        byte[] result = cipher.doFinal(Base64.decodeBase64(text));
//        return new String(result);
//    }


    /**
     * 公钥解密
     *
     * @param text 待解密的信息
     * @return 解密后的文本
     */
    public static String decryptByPublicKey(String text,String key) throws Exception {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(key));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        byte[] result = cipher.doFinal(Base64.decodeBase64(text));
        return new String(result);
    }

    /**
     * 私钥加密
     *
     * @param privateKeyString 私钥
     * @param text             待加密的信息
     * @return 加密后的文本
     */
    public static String encryptByPrivateKey(String privateKeyString, String text) throws Exception {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyString));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(text.getBytes());
        return Base64.encodeBase64String(result);
    }

    /**
     * 私钥解密
     *
     * @param privateKeyString 私钥
     * @param text             待解密的文本
     * @return 解密后的文本
     */
    public static String decryptByPrivateKey(String privateKeyString, String text) throws Exception {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyString));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(Base64.decodeBase64(text));
        return new String(result);
    }

    /**
     * 公钥加密
     *
     * @param publicKeyString 公钥
     * @param text            待加密的文本
     * @return 加密后的文本
     */
    public static String encryptByPublicKey(String publicKeyString, String text) throws Exception {
        X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyString));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] result = cipher.doFinal(text.getBytes());
        return Base64.encodeBase64String(result);
    }

    /**
     * 构建RSA密钥对
     *
     * @return 生成后的公私钥信息
     */
    public static RsaKeyPair generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
        String publicKeyString = Base64.encodeBase64String(rsaPublicKey.getEncoded());
        String privateKeyString = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
//        System.out.println(publicKeyString);

//        System.out.println("----------");
//        System.out.println(privateKeyString);

        return new RsaKeyPair(publicKeyString, privateKeyString);
    }

    /**
     * RSA密钥对对象
     */
    public static class RsaKeyPair {
        private final String publicKey;
        private final String privateKey;

        public RsaKeyPair(String publicKey, String privateKey) {
            this.publicKey = publicKey;
            this.privateKey = privateKey;
        }

        public String getPublicKey() {
            return publicKey;
        }

        public String getPrivateKey() {
            return privateKey;
        }
    }

    //
    public static void main(String[] args) {

//        try {
//            RsaUtils.generateKeyPair();
//        } catch (NoSuchAlgorithmException e) {
//            throw new RuntimeException(e);
//        }
//        try {
//            String a = ConfigTools.encrypt("MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBANObDz93ky/znoxHwiLP2yEstb6LsyJBQOnMbsC2oUrLpBucpkWSy5vDkq7nDiFBY0LComnUb9pG/r2peFAhj2ylV4fZTu2UuKVMaN4Byh+tc1KExhi2Kqt9Jgs7b6CM9mCVttQZj33LgkA8vgIksrE85qSMcO7csY7Wxh7n7wkTAgMBAAECgYEA0wVzM0u/0LYWiraU97ppQLAhnqAaSDLi1UU1vaFjP//M7GxPtFosCm4CvcFV6fwXTOBkrz1XPkpGiEWU4fRV3aWsMwTxgYZt9OPT55zoKPbxfaVWe3qtLhwrvt8AYPDzIQG4Lu1AXLWBva+M8Sk63fj1jeztu9eOJzi6f9PCDWECQQD6Ege0F580B9tofWJzYLYakCZ6lxDCZ95C4awtJlElk0Sj5nu++JxGY3ePB6GxcPYko91xNScPVH8M+OHKOq0PAkEA2J+Kw4oaIAPU9etYBJy/zGkpqa8NJkGloRLNKPTQDIMkgv07RLQ0LV6iYX4oNYpO7GBlC81FVFX4BjX+NzhrvQJBAIcq978Aha06Ef6Ix45V2BjDkgjxXr22Jw0/rjE5ZONKlu+AxaKT/uSNHzLQjTW8OU/Uwv1OHa7LnWEFpgYJcUECQQCJC/aIWzjIBGSY6LmYwWp+chHPrlXNXD7jNrfhL3DoWZeh33+9qZxRD8v/jgb2SHhCB4ImA0nXX0Q4+bPJT8KpAkEAs0Ni/OaCKoFMxw5BbIIcXr6DKFR6PODr6uUm634UN36FE2NDU3LZRiu7NotcXaI6/v7Hc+LnyK271oyqULWPiw==",
//                    "123456");
//            System.out.println(a);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//        try {
//            //RsaUtils.generateKeyPair();
//            //公：
//            String p = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCGWu6fAHSPtJkfivtfoWsFbDEML+NnrBXfNXtPCM6jPEb0qhph8mKI7O6HAHh44byvteXB/TH60eSYG9OzTE2mrhBDx/O9nywWKH52Vz0RdNeybtilfC4nGwpnqooP7FimRsaSxmu3CpEy1V5AhamQ1IeNm3YH12kJnwL8nWeSwIDAQAB";
//            String s = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMIZa7p8AdI+0mR+K+1+hawVsMQwv42esFd81e08IzqM8RvSqGmHyYojs7ocAeHjhvK+15cH9MfrR5Jgb07NMTaauEEPH872fLBYofnZXPRF017Ju2KV8LicbCmeqig/sWKZGxpLGa7cKkTLVXkCFqZDUh42bdgfXaQmfAvydZ5LAgMBAAECgYAMn2aYHBRqPdek3Wex7DZ5OHfkal8qsJU7O00WPoDz/9J2Qr7dDg2XRDcd9VBSBl/yTWLr2YKbtbtT052pfEKk80IPtx1K+Nru55XbWOu5ScPJAVgL3bF0jzFjcHPHFAB9+ZDNnZYmNP2mKE38JqNN2ql99JIzGNE+hFNtkHJLEQJBAPlS1xKgEws/08JXJCxja3Ycb2LY5O0V2KQNHZm7L3ReUU88qpPXSikCLeLxWy9p7LIQkQ+Arum13g0Lcy3ayRUCQQDHTAIAhdsGJyHfKpVb0lvpt/hYC5+NYrpzRNIBYGdy0D7vXPviwtODO5oYEx7d4TFXJthZu5EP6eLWK2hc0eHfAkEAjn6aDTsPp05DaL8FHZl0wXxe7M+phxcFSj10vXgOFyQQtIintPdGm0lzkFEBHIgdj2eIgKO7VDdtQWdZ3Ms+QQJBALwtEFbeDIgquti0pIImhZKQmnTHxMcCyXm9KW0TUZoe9s2bxlm+C2iGBmFk7GgkESpxCybu63FTLVN7ePbrVZECQDdeHukP0V0VU+/aEzEOKMi8SEpe3XGFzO5S1ocbWvwKsWY5dLwvJF9Pvxj8ZH7G94UnrO2ek5mxUktTH2WEB6E=";
//
//            //3706,2162,4116,4116,205C,20D2,3E2A,FD72,30CA,1042,215E,3AE4,2350,332A::7103,2037,F0A9,21A9,1155,5351,F061,1B06,4355,3357,F0DF,20D5,5009,39F1,0B0D,2603,3FFF,FD45,1FE5
//
//            System.out.println(RsaUtils.encryptByPublicKey(p,"3706,2162,4116,4116,205C,20D2,3E2A,FD72,30CA,1042,215E,3AE4,2350,332A::7103,2037,F0A9,21A9,1155,5351,F061,1B06,4355,3357,F0DF,20D5,5009,39F1,0B0D,2603,3FFF,FD45,1FE5"));
//
//            //System.out.println(RsaUtils.decryptByPublicKey(p,"1212121"));
//        } catch (NoSuchAlgorithmException e) {
//            throw new RuntimeException(e);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
    }
}